package com.cloudwise.servlet;

import com.cloudwise.service.PersonInfoService;
import com.cloudwise.service.impl.PersonInfoServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈
 * @date ：Created in 2021/1/25 14:42
 * @description：人员信息业务控制器
 * @modified By：
 * @version: 1
 */
//@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private PersonInfoService personInfoService=new PersonInfoServiceimpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Enumeration<String> attributeNames = req.getParameterNames();
        //封装所有的请求参数名，参数值
        Map map = new HashMap();
       while(attributeNames.hasMoreElements()) {
           /*System.out.println(attributeNames.nextElement());*/
           String  key=attributeNames.nextElement();
           String value = req.getParameter(key);
           map.put(key,value);
       }
       //去数据库判断用户是否合法，用户编号和姓名作为查询条件，如果能查询到数据
        Map<String, Object> person = personInfoService.findPersonByIdAndName(map);
        System.out.println("sessionId："+req.getSession().getId());
        if(person!=null){
            HttpSession session= req.getSession();
            //合法 进入显示所有的页面
            //设置session值
            session.setAttribute("xxx1","ooo1");
            session.setAttribute("xxx2","ooo2");
            session.setAttribute("xxx3","ooo3");
            //设置session的有效期
           // session.setMaxInactiveInterval(60);
            session.removeAttribute("message");
            session.setAttribute("person_id",map.get("person_id"));
            //将用户id保存到cookie中
           /* Cookie cookie = new Cookie("person_id",map.get("person_id").toString());
            //设置cookie的有效期,单位为秒
            cookie.setMaxAge(600);
            //设置cookie的域名
            cookie.setDomain("localhost");
            //将cookie响应回浏览器
            resp.addCookie(cookie);*/
            req.getRequestDispatcher("person").forward(req,resp);
            String xxx = req.getServletContext().getInitParameter("xxx");
            System.out.println("loginservlet："+xxx);
            String ooo = getInitParameter("ooo");
            System.out.println("局部变量："+ooo);
        }else{
            //非法重新登录（提示错误信息）
            String message="用户编号或用户名错误，请检查";
            req.getSession().setAttribute("message",message);
            resp.sendRedirect("login.jsp");

        }




    }

}
